<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
         <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['aipay:apiRule:add']">新增</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="接口类型" align="center" prop="typeId" />
      <el-table-column label="调用方式" align="center" prop="invokeType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.aipay_invoke_type" :value="scope.row.invokeType"/>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="ctime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ctime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="mtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.mtime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['aipay:apiRule:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['aipay:apiRule:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="支付类型" prop="typeId">
          <el-select v-model="form.typeId" @change="handleSelectType" placeholder="支付类型" size="small" :clearable="true">
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调用方式" prop="invokeType">
          <el-select v-model="form.invokeType" placeholder="调用方式" size="small" :clearable="true">
            <el-option
              v-for="dict in dict.type.aipay_invoke_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="content">
           <el-table :data="channelInfo" ref="ruleTable">
              <el-table-column label="是否选择" align="center">
                <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checked"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="接口账户名" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.name"
                    placeholder="请输入接口账户名"
                    clearable
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="权重【随机轮询有效】" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.weight"
                    placeholder="请输入默认值"
                    clearable
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="排序" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.sort"
                    placeholder="请输入排序"
                    clearable
                    size="small"
                  />
                </template>
              </el-table-column>
            </el-table>
            <div class="tag">
              <span>1、关于随机轮询权重的说明，权重的值默认为1，代表各个通道随机所占的几率是一样的。</span>
              <span>2、权重越大代表该接口账户被选中的几率也就越大。</span>
            </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPaymentParamsAll } from "@/api/aipay/paymentParams";
import { listPaymentTypeAll } from "@/api/aipay/paymentType";
import { listPaymentAccountByType } from "@/api/aipay/paymentAccount";
import { listPaymentRule, getPaymentRule, addPaymentRule, updatePaymentRule, delPaymentRule  } from "@/api/aipay/paymentRule";

export default {
  name: "PaymentAccount",
  dicts: ['sys_bool_status', 'aipay_invoke_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //表格数据
      postList: [],
      paramsList: [],
      typeList: [],
      accountList: [],
      content: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSetting: false,
      settingTitle: '',
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        name: undefined,
      },
      content: [],
      channelInfo: [],
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        typeId: undefined,
        invokeType: undefined,
        rule: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "接口类型不能为空", trigger: "change" }
        ],
        invokeType: [
          { required: true, message: "调用方式不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getAllPaymentParamsAll();
    this.getAllPaymentTypeAll();
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listPaymentRule(this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAllPaymentTypeAll(){
      listPaymentTypeAll().then(response => {
        this.typeList = response.data;
        this.form.typeId = this.form.typeId + '';
      });
    },
    getAllPaymentParamsAll(){
      listPaymentParamsAll().then(response => {
        this.paramsList = response.data;
      });
    },
    getListPaymentAccountByType(typeId){
      listPaymentAccountByType({typeId: typeId}).then(response => {
        let accountList = response.data;
        if(accountList && accountList.length > 0){
          let exitsList = [];
          if(this.form.rule){
            exitsList = JSON.parse(this.form.rule);
          }
          let list = [];
          let checkList = [];
          for(let i = 0; i < accountList.length; i++){
            let exitsObj = null;
            for(let j = 0; j < exitsList.length; j++){
              if(accountList[i].id === exitsList[j].id){
                exitsObj = exitsList[j];
                checkList.push(exitsObj);
                break;
              }
            }
            if(exitsObj){
              list.push(exitsObj);
            } else {
              list.push({checked: false, id: accountList[i].id, name: accountList[i].name, weight: 1, sort: i + 1});
            }
          }
          this.channelInfo = list;
          checkList.forEach(item => {
            console.log("item:", item)
            this.$refs.ruleTable.toggleRowSelection(1, true);
          })
        }
      });
    },
    handleSelectType(id){
      if(id){
        this.getListPaymentAccountByType(id);
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        typeId: undefined,
        invokeType: undefined,
        rule: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if(selection.length > 0){
        this.form.rule = JSON.stringify(selection);
      } else {
        this.form.rule = "";
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加接口规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getPaymentRule(row.id).then(response => {
        this.form = response.data;
        this.form.invokeType = this.form.invokeType + '';
        this.getListPaymentAccountByType(this.form.typeId);
        this.open = true;
        this.title = "修改接口规则";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let selection = this.channelInfo.filter(item => item.checked);
          if(selection.length > 0){
            this.form.rule = JSON.stringify(selection);
          } else {
            this.form.rule = "";
          }
          if (this.form.id != undefined) {
            if(!this.form.rule){
              this.msgError("请选择规则");
              return;
            }
            updatePaymentRule(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPaymentRule(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPaymentRule(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    }
    
  }
};
</script>
<style>
.tag{
  background: #409EFF;
  display: flex;
  flex-direction: column;
  color: #fff;
  border-radius: 4px;
  padding: 5px;
}
</style>
